package Power;

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

import Constructions.Construction;
import Main.SpaceGame;

public class PowerManager 
{
	private SpaceGame main;
	public ArrayList<PowerNode> nodeList = new ArrayList<PowerNode>();
	public ArrayList<Generator> generatorList = new ArrayList<Generator>();
	boolean hasPowerCore = false;
	int updateCnt = 5;
	public int maxPowerNodes = 5, currentPowerNodes;

	public PowerManager(SpaceGame main)
	{
		maxPowerNodes = 5;
		this.main = main;
		add(new PowerCore(44, 34, main));
	}
	
	public void update()
	{
		if (updateCnt > 1)
			updateCnt--;
		else
		{
			try{
			for(PowerNode p:nodeList)
			{
				p.update();
			}
			}
			catch(ConcurrentModificationException e)
			{}
			updateCnt = 5;
		}
		
		maxPowerNodes = 5;
		try{
		for(Generator g: generatorList)
		{
			maxPowerNodes += g.getNodesSupported();
			if(g instanceof SolarPanel)
			{
				if(((SolarPanel) g).checkSupport() == false)
				{
					generatorList.remove(g);
				}
			}
		}
		}catch(ConcurrentModificationException e){}
		
	}
	
	public void draw(Graphics g)
	{
		for(PowerNode p:nodeList)
		{
			p.draw(g);
		}
		for(Generator f:generatorList)
		{
			f.draw(g);
		}
	}
	
	public void add(PowerNode c)
	{
		nodeList.add(c);
		for (int i = c.getX();i<c.getX()+c.getWidth();i++)
		{
			for (int j = c.getY();j<c.getY()+c.getHeight();j++)
			{
				main.world.tiles[i][j].setHasConstruction(true);
			}
		}
	}
	
	public void remove(int x,int y)
	{
		try
		{
			for (PowerNode c:nodeList)
			{
				if (c.getX() == x && c.getY() == y)
				{
					nodeList.remove(c);
					for (int i = c.getX();i<c.getX()+c.width;i++)
					{
						for (int j = c.getY();j<c.getY()+c.height;j++)
						{
							main.world.tiles[i][j].setHasConstruction(false);
						}
					}
				}
			}
		}
		catch(ConcurrentModificationException e)
		{
			
		}
	}
	
	public void addGenerator(Generator c)
	{
		generatorList.add(c);
		for (int i = c.getX();i<c.getX()+c.getWidth();i++)
		{
			for (int j = c.getY();j<c.getY()+c.getHeight();j++)
			{
				main.world.tiles[i][j].setHasConstruction(true);
			}
		}
	}
	
	public void removeGenerator(int x,int y)
	{
		try
		{
			for (Generator c:generatorList)
			{
				if (c.getX() == x && c.getY() == y)
				{
					generatorList.remove(c);
					for (int i = c.getX();i<c.getX()+c.width;i++)
					{
						for (int j = c.getY();j<c.getY()+c.height;j++)
						{
							main.world.tiles[i][j].setHasConstruction(false);
						}
					}
				}
			}
		}
		catch(ConcurrentModificationException e)
		{
			
		}
	}
	
	public int getMaxPowerNodes() 
	{
		return maxPowerNodes;
	}

	public void setMaxPowerNodes(int maxPowerNodes) 
	{
		this.maxPowerNodes = maxPowerNodes;
	}

	public int getCurrentPowerNodes() 
	{
		return currentPowerNodes;
	}

	public void setCurrentPowerNodes(int currentPowerNodes) 
	{
		this.currentPowerNodes = currentPowerNodes;
	}
}
